package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Region;
import cn.wolfcode.luowowo.article.mapper.DestinationMapper;
import cn.wolfcode.luowowo.article.mapper.RegionMapper;
import cn.wolfcode.luowowo.article.service.IRegionService;
import cn.wolfcode.luowowo.common.query.QueryObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private DestinationMapper destinationMapper;

    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Region> list = regionMapper.query4List(qo);
        return new PageInfo(list);
    }

    @Override
    public List<Destination> listDestByRegionId(Long rid) {
        List<Destination> list = new ArrayList<>();
        //先获取当前id对应的区域
        Region region = regionMapper.selectByPrimaryKey(rid);
        //获取目的地id数组
        Long[] refIds = region.getRefIds();
        if (refIds != null && refIds.length > 0) {
            for (Long refId : refIds) {
                Destination destination = destinationMapper.selectByPrimaryKey(refId);
                if (destination != null) {
                    list.add(destination);
                }
            }
        }
        return list;
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (region.getId() == null) {
            //保存操作
            regionMapper.insert(region);
        } else {
            //修改操作
            regionMapper.updateByPrimaryKey(region);
        }
    }

    @Override
    public List<Region> listAll() {
        return regionMapper.selectAll();
    }

}
